import { Request, Response, NextFunction } from 'express'
import { ZodEffects, ZodError, ZodTypeAny } from 'zod'
import { IValidationMiddlewareOptions } from '@/types/common'
import RequestValidateError from '@/errors/RequestValidateError'
import { errorRequestMiddleware } from './http-request'
import { getParamsFromRequest } from '@/utils'

// 生成校验中间件
export const generateValidatorMiddleware = (
  zodSchema: ZodEffects<ZodTypeAny>,
  option: IValidationMiddlewareOptions = { isAsync: true }
) => {
  return async (req: Request, res: Response, next: NextFunction) => {
    // 请求体校验
    const reqParams = getParamsFromRequest(req)
    try {
      if (option.isAsync) {
        // 异步校验
        await zodSchema.parseAsync(reqParams)
      } else {
        // 同步校验
        zodSchema.parse(reqParams)
      }
      next()
    } catch (e) {
      if (e instanceof ZodError) {
        // 校验失败
        const error = new RequestValidateError(e)
        // 执行异常处理中间件
        errorRequestMiddleware(error, req, res, next)
      } else {
        next(e)
      }
    }
  }
}
